package com.xhu.collegestudentrentalsystem.springservice;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xhu.collegestudentrentalsystem.module.user.dao.UserDAO;
import com.xhu.collegestudentrentalsystem.module.user.entity.User;
import com.xhu.collegestudentrentalsystem.util.constant.EntityProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;

/**
 * @author zhu huilin
 * @date 2023/3/4 15:54
 * 自定义用户信息验证
 * 从数据库中取出数据判断用户登录是否能够成功
 */
@Service
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UserDAO userDAO;

    /**
     *  重写登录认证、权限认证的逻辑
     *      用户名、密码、权限 全部使用自己的数据库中的数据
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(EntityProperty.user.USERNAME, username);
        User user = userDAO.selectOne(queryWrapper);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        /*
            角色暂未设置权限，创建一个空的权限集合即可
         */
        // 权限集合
        Collection<GrantedAuthority> authorities = new HashSet<>();

        // 存入Spring Security中UserDetails的默认实现类User中，返回
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(), "{noop}" + user.getPassword(),
                true, true, true, true,
                authorities
        );

    }


}
